<template>
  <div ref="fixed" :style="containerStyle">
    <div :style="style">
      <slot />
    </div>
  </div>
</template>

<script>
export default {
  name: 'FixedPage',

  props: {
    fixedStyle: {
      type: Object,
      default : () => {}
    }
  },

  data() {
    return {
      style: {},
      height: 0
    };
  },

  computed: {
    containerStyle() {
      const { height } = this;
      if (!height) return '';
      return { height: `${height}px` };
    }
  },

  mounted() {
    this.init();
  },

  beforeDestroy() {
    this.removeListeners();
  },

  methods: {
    init() {
      if (process.server) return;
      this.check();
      window.addEventListener('scroll', this.check);
    },

    removeListeners() {
      if (process.server) return;
      window.removeEventListener('scroll', this.check);
    },
    check() {
      const { height, bottom } = this.$el.getBoundingClientRect();
      const { innerHeight } = window;
      this.height = height;

      if (bottom > innerHeight) {
        // 内容过长
        this.style = { position: 'fixed', bottom: 0, ...this.fixedStyle };
      } else {
        // 正常
        this.style = {};
      }
    }
  }
};
</script>
